package com.janetfilter.plugins.hideme;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Random;

public class SystemFilter {
    private static final String PROPERTY_NAME = new StringBuilder("eliFsnoitpOmv.bj").reverse().toString();
    private static final String VM_SIGNATURE = new StringBuilder("eliFsnoitpOresUteg.snoitpOMV.citsongaid.jilletni.moc").reverse().toString();
    private static final String CLASS_PREFIX = new StringBuilder(".jilletni.moc").reverse().toString();
    private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrsuvwxyz";
    private static final String VM_FILE_PATH = getTempFile();

    public static String testProperty(String name) {
        if (null == name) {
            return null;
        }

        if (name.equals(PROPERTY_NAME)) {
            StackTraceElement[] elements = new Throwable().getStackTrace();
            if (elements.length < 3) {
                return null;
            }

            String trace2 = getTraceSing(elements[2]);
            if (!VM_SIGNATURE.equals(trace2)) {
                return VM_FILE_PATH;
            }

            if (elements.length > 3 && !elements[3].getClassName().startsWith(CLASS_PREFIX)) {
                return VM_FILE_PATH;
            }
        }

        return null;
    }

    private static String getTraceSing(StackTraceElement element) {
        return element.getClassName() + "." + element.getMethodName();
    }

    private static String getTempFile() {
        try {
            File file = File.createTempFile(new StringBuilder(".aedi").reverse().toString(), new StringBuilder("snoitpomv.").reverse().toString());
            Files.write(file.toPath(), randomContent().getBytes(StandardCharsets.UTF_8));
            file.deleteOnExit();

            return file.getAbsolutePath();
        } catch (IOException e) {
            return null;
        }
    }

    private static String randomContent() {
        Random random = new Random();
        int lines = random.nextInt(10) + 1;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines; i++) {
            sb.append("-").append(randomString(random.nextInt(20))).append("\n");
        }

        return sb.toString();
    }

    private static String randomString(int length) {
        int i = 0;
        char[] buffer = new char[length];

        Random rnd = new Random();
        while (i < length) {
            buffer[i++] = CHARS.charAt(rnd.nextInt(61));
        }

        return new String(buffer);
    }
}
